<template>
  <app-loader v-if="loading"></app-loader>
  <app-page title="Список заявок" v-else>
    <template #header>
      <div class="button btn primary" @click="modal = true">Создать</div>
    </template>

    <request-filter v-model="filter"/>
    <request-table :requests="requests"></request-table>


    <teleport to="body">
      <app-modal v-if="modal" title="Создать заявку" @close="modal = false">
        <request-modal @created="modal = false"></request-modal>
      </app-modal>
    </teleport>
  </app-page>
</template>

<script>
import AppPage from "@/components/ui/AppPage.vue";
import RequestTable from "@/components/request/RequestTable.vue";
import {computed, onMounted, ref} from "vue";
import AppModal from "@/components/ui/AppModal.vue";
import RequestModal from "@/components/request/RequestModal.vue";
import {useStore} from "vuex";
import AppLoader from "@/components/ui/AppLoader.vue";
import RequestFilter from "@/components/request/RequestFilter.vue";

export default {
  name: 'Home',
  components: {
    RequestFilter,
    AppLoader,
    AppPage,
    RequestTable,
    AppModal,
    RequestModal
  },
  setup(){
    const modal = ref(false);

    const store = useStore();

    const requests = computed(() => store.getters['request/requests']
        .filter( request => {
          if(filter.value.name){
            return request.FIO.includes(filter.value.name)
          }
          return request
        })
        .filter( request => {
          if(filter.value.status){
            return request.status.includes(filter.value.status)
          }
          return request
        })
    )


    const loading = ref(false);
    onMounted(async () => {
      loading.value = true;
      await store.dispatch('request/load');
      loading.value = false;
    })

    const filter = ref({});


    return {
      modal, requests, loading,
      filter
    };
  }
}
</script>
